<?php


namespace app\zhongcan\controller;

use app\zhongcan\model\BannerModel;
use app\zhongcan\validate\BannerValidate;
use cmf\controller\AdminBaseController;

class BannerController extends AdminBaseController
{
    //显示banner图
    public function index(){
        $list = BannerModel::order(['list_order' => 'DESC'])
                ->paginate(4);
        $this->assign('list',$list);
        return $this->fetch();
    }
    //上传图片
    public function add(){
        $list = BannerModel::select();
        return $this->fetch('add',['list'=>$list]);
//        return $this->fetch('add');
    }
    //添加图片
    public function addPost(){
        $image = input('image');
        $url = cmf_get_image_url($image);
        if(BannerModel::create([
            'image' => $url
        ])){
            $this->success('添加成功');
        }else{
            $this->error('添加失败');
        }
    }
    //修改页面显示
    public function edit(){
        $id = input('id');
        $banner = BannerModel::find($id);
        $this->assign('banner',$banner);
        return $this->fetch();
    }
    //修改方法
    public function editPost(){
        $data = input('post.');
        //验证器
        $validate = new BannerValidate();
        $res = $validate->scene('edit')->check($data);
        if(!$res){
            $this->error($validate->getError());
        }
//        查询用户是否存在
        $edit = BannerModel::find($data['id']);
        if(!$edit){
            $this->error('未查询到该数据');
        }
        $edit->image= $data['image'];
        $edit->url= $data['url'];
        if ($edit->save()) {
            $this->success('修改成功','Banner/index');
        } else {
            $this->error('修改失败');
        }
    }
    //删除
    public function delete(){
        $id = input('id/d','');
        if (!$id){
            $this->error('参数错误');
        }
        if (BannerModel::destroy($id)){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    //排序
    public function order(){
        parent::listOrders(new BannerModel());
        $this->success('排序成功');
    }

}